using System;
using System.Collections.Generic;
using System.Text;

using Irrlicht.Scene;
using Irrlicht.Video;
using Irrlicht;
using Irrlicht.Core;

using Mud.Common.Physical;

namespace Mud.Client.WinApplication.Graphics
{
    public class CreatureModel : Model
    {

        public Creature Creature
        {
            get { return _creature; }
        }
        private Creature _creature;


        public CreatureModel(IrrlichtDevice device, Creature creature)
            : base(device)
        {
            _creature = creature;
        }

        public override void AddToScene()
        {
            _creature.GameObjectChanged += CreatureChanged;
            Vector3D position = new Vector3D(_creature.Location.X, _creature.Location.Y, 0);
            Vector3D rotation = DetermineRotation(_creature);
            Vector3D scale = new Vector3D(1, 1, 1);

            IAnimatedMesh mesh = Device.SceneManager.GetMesh(@"Meshes\Player.obj");
            Node = Device.SceneManager.AddAnimatedMeshSceneNode(mesh, null, -1, position, rotation, scale);
            ITexture texture = Device.VideoDriver.GetTexture(@"Textures\Dirt.bmp");
            Node.SetMaterialTexture(0, texture);
        }

        public override void RemoveFromScene()
        {
            base.RemoveFromScene();
            _creature.GameObjectChanged -= CreatureChanged;
        }

        private void CreatureChanged(GameObject o)
        {
            Node.Rotation = DetermineRotation(_creature);
            Node.Position = new Vector3D(_creature.Location.X, _creature.Location.Y, 0); 
        }


        private Vector3D DetermineRotation(Creature c)
        {
            int z;
            switch (c.Orientation)
            {
                case Orientation.North:
                    z = 0;
                    break;
                case Orientation.NorthWest:
                    z = -45;
                    break;
                case Orientation.West:
                    z = -90;
                    break;
                case Orientation.SouthWest:
                    z = -135;
                    break;
                case Orientation.South:
                    z = 180;
                    break;
                case Orientation.SouthEast:
                    z = 135;
                    break;
                case Orientation.East:
                    z = 90;
                    break;
                case Orientation.NorthEast:
                    z = 45;
                    break;
                default:
                    throw new ArgumentOutOfRangeException("c.Orientation");
            }
            Vector3D vector = new Vector3D(90, 0, z);
            return vector;
        }

    }
}
